let editor;
let currentNote = null;
let noteTree = [];
let isPreviewVisible = true;

// 初始化编辑器
function initializeEditor() {
    editor = monaco.editor.create(document.getElementById('editor'), {
        value: '',
        language: 'markdown',
        theme: 'vs',
        minimap: { enabled: false },
        wordWrap: 'on',
        fontSize: 14,
        lineNumbers: 'on',
        scrollBeyondLastLine: false,
    });

    // 监听编辑器内容变化，更新预览
    editor.onDidChangeModelContent(() => {
        if (isPreviewVisible) {
            updatePreview();
        }
        if (currentNote) {
            saveNote();
        }
    });

    // 加载保存的笔记
    loadNotes();

    // 初始化预览状态
    updatePreviewVisibility();
}

// 等待 Monaco Editor 加载完成
window.onload = () => {
    // 初始化事件监听
    initializeEventListeners();
    
    // 配置 Monaco Editor
    require(['vs/editor/editor.main'], function() {
        initializeEditor();
    });
};

// 初始化事件监听
function initializeEventListeners() {
    // 监听预览切换按钮
    document.getElementById('previewToggleBtn').addEventListener('click', togglePreview);
    
    // 监听新建文件夹按钮
    document.getElementById('newFolderBtn').addEventListener('click', createFolder);
    
    // 监听新建笔记按钮
    document.getElementById('newNoteBtn').addEventListener('click', () => createNote());
    
    // 监听导出按钮
    document.getElementById('exportBtn').addEventListener('click', exportNote);
    
    // 监听导入按钮
    document.getElementById('importBtn').addEventListener('click', () => importNote());
    
    // 监听保存按钮
    document.getElementById('saveBtn').addEventListener('click', saveNote);
    
    // 监听标题变化
    document.getElementById('noteTitle').addEventListener('input', () => {
        if (currentNote) {
            saveNote();
        }
    });
}

// 更新Markdown预览
function updatePreview() {
    const content = editor.getValue();
    const preview = document.querySelector('.markdown-preview');
    if (preview) {
        preview.innerHTML = marked.parse(content);
    }
}

// 切换预览显示状态
function togglePreview() {
    isPreviewVisible = !isPreviewVisible;
    updatePreviewVisibility();
    
    // 更新编辑器布局
    editor.layout();
}

// 更新预览可见性
function updatePreviewVisibility() {
    const container = document.querySelector('.editor-container');
    const previewBtn = document.getElementById('previewToggleBtn');
    
    if (isPreviewVisible) {
        container.classList.remove('preview-hidden');
        previewBtn.classList.add('active');
        updatePreview();
    } else {
        container.classList.add('preview-hidden');
        previewBtn.classList.remove('active');
    }
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
    if (editor) {
        editor.layout();
    }
});

// 保存笔记
async function saveNote() {
    if (!currentNote) return;

    const title = document.getElementById('noteTitle').value;
    const content = editor.getValue();
    
    currentNote.title = title;
    currentNote.content = content;
    currentNote.updatedAt = new Date().toISOString();

    await saveNotes();
    updateFileTree();
}

// 创建新笔记
async function createNote(folderId = null) {
    const note = {
        id: Date.now().toString(),
        title: 'New Note',
        content: '',
        folderId,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };

    noteTree.push(note);
    await saveNotes();
    updateFileTree();
    loadNote(note);
    
    // 聚焦标题输入框
    const titleInput = document.getElementById('noteTitle');
    titleInput.focus();
    titleInput.select();
}

// 创建新文件夹
async function createFolder() {
    const folderName = prompt('Enter folder name:');
    if (!folderName) return;

    const folder = {
        id: 'folder_' + Date.now(),
        name: folderName,
        type: 'folder',
        createdAt: new Date().toISOString()
    };

    noteTree.push(folder);
    await saveNotes();
    updateFileTree();
}

// 加载笔记
function loadNote(note) {
    if (!note) return;
    
    currentNote = note;
    document.getElementById('noteTitle').value = note.title || '';
    editor.setValue(note.content || '');
    updatePreview();
    
    // 更新选中状态
    const allNotes = document.querySelectorAll('.tree-item.note');
    allNotes.forEach(el => {
        el.classList.remove('active');
        if (el.dataset.noteId === note.id) {
            el.classList.add('active');
        }
    });
}

// 保存所有笔记到存储
async function saveNotes() {
    await chrome.storage.local.set({ notes: noteTree });
}

// 从存储加载笔记
async function loadNotes() {
    const data = await chrome.storage.local.get('notes');
    noteTree = data.notes || [];
    updateFileTree();
}

// 更新文件树显示
function updateFileTree() {
    const treeContainer = document.getElementById('fileTree');
    treeContainer.innerHTML = '';

    // 先渲染文件夹
    const folders = noteTree.filter(item => item.type === 'folder');
    folders.forEach(folder => {
        const folderElement = createFolderElement(folder);
        treeContainer.appendChild(folderElement);
    });

    // 渲染未分类的笔记
    const unorganizedNotes = noteTree.filter(item => !item.type && !item.folderId);
    unorganizedNotes.forEach(note => {
        const noteElement = createNoteElement(note);
        treeContainer.appendChild(noteElement);
    });
}

// 创建文件夹元素
function createFolderElement(folder) {
    const div = document.createElement('div');
    div.className = 'tree-item folder';
    div.dataset.folderId = folder.id;
    
    const header = document.createElement('div');
    header.className = 'folder-header';
    
    const icon = document.createElement('span');
    icon.className = 'icon mdi mdi-folder';
    
    const name = document.createElement('span');
    name.className = 'name';
    name.textContent = folder.name;
    
    const actions = document.createElement('div');
    actions.className = 'actions';
    
    const addNoteBtn = document.createElement('button');
    addNoteBtn.className = 'icon-button';
    addNoteBtn.innerHTML = '<span class="mdi mdi-note-plus"></span>';
    addNoteBtn.title = 'New Note';
    addNoteBtn.onclick = (e) => {
        e.stopPropagation();
        createNote(folder.id);
    };
    
    const importBtn = document.createElement('button');
    importBtn.className = 'icon-button';
    importBtn.innerHTML = '<span class="mdi mdi-upload"></span>';
    importBtn.title = 'Import Note';
    importBtn.onclick = (e) => {
        e.stopPropagation();
        importNote(folder.id);
    };
    
    actions.appendChild(addNoteBtn);
    actions.appendChild(importBtn);
    
    header.appendChild(icon);
    header.appendChild(name);
    header.appendChild(actions);
    
    const content = document.createElement('div');
    content.className = 'folder-content';
    
    // 渲染文件夹中的笔记
    const notes = noteTree.filter(item => !item.type && item.folderId === folder.id);
    notes.forEach(note => {
        const noteElement = createNoteElement(note);
        content.appendChild(noteElement);
    });
    
    div.appendChild(header);
    div.appendChild(content);
    
    // 切换文件夹展开/折叠
    header.onclick = () => {
        div.classList.toggle('expanded');
    };
    
    return div;
}

// 创建笔记元素
function createNoteElement(note) {
    const div = document.createElement('div');
    div.className = 'tree-item note';
    div.dataset.noteId = note.id;
    
    const icon = document.createElement('span');
    icon.className = 'icon mdi mdi-note-text';
    
    const name = document.createElement('span');
    name.className = 'name';
    name.textContent = note.title;
    
    div.appendChild(icon);
    div.appendChild(name);
    
    div.onclick = () => loadNote(note);
    
    return div;
}

// 导出笔记
function exportNote() {
    if (!currentNote) return;
    
    const blob = new Blob([currentNote.content], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${currentNote.title}.md`;
    a.click();
    URL.revokeObjectURL(url);
}

// 导入笔记
async function importNote(folderId = null) {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.md,.markdown';
    
    input.onchange = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = async (e) => {
            const content = e.target.result;
            const title = file.name.replace(/\.[^/.]+$/, ""); // 移除文件扩展名
            
            const note = {
                id: Date.now().toString(),
                title,
                content,
                folderId,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };
            
            noteTree.push(note);
            await saveNotes();
            updateFileTree();
            loadNote(note);
        };
        reader.readAsText(file);
    };
    
    input.click();
}
